<template>
  <div class="block">
    <el-scrollbar style="height: 100%">
        <el-row
          v-for="(step, index) in route.devs"
          ref="timeline"
          :key="index">
      <!-- <el-timeline>
        <el-timeline-item
          v-for="(step, index) in route.devs"
          ref="timeline"
          :key="index"
          placement="top"
          icon="icon success"
          :type="getType(step.state, index)"
          size="large"
          @click.native="onStepClick(index)" > -->
          <div class="resttime"
               v-if="step.name != ''">
               <strong>
                 <i class="el-icon-location-outline" type="primary"></i>
                  {{ step.name }}
               </strong>
                {{ step.cycleText}}
            <!-- <el-tag size="medium" effect="plain" style="float:right;" :type="getTag(step).type">{{ getTag(step).label }}</el-tag> -->
            <div style="float:right;">
              <div style="display:inline-block;margin-right:5px;" class="grid-content bg-purple">{{ $t("openatc.greenwaveoptimize.pattern") }}: {{ step.terminalname }}</div>
              <!-- <el-button  v-show="tabName === 'second'"
                          style="float: right;margin-bottom:5px;margin-top:-5px;"
                          :type="getButtonType(step)"
                          size="small"
                          @click="executeViproute(step)">
                <template v-if="!step.state || step.state === 0">
                  {{ $t("openatc.dutyroute.executen") }}
                </template>
                <template v-else>
                  {{ $t("openatc.dutyroute.cancel") }}
                </template>
              </el-button> -->
            </div>
          </div>
          <div class="resttime" style="border:0px solid red;"
               v-if="step.name != ''">
            <div style="display:flex;justify-content:space-between;">
              <div style="display:inline-block;margin-right:40px;" class="grid-content bg-purple">
                 {{ getControlName(step.control) }} -- {{ getContent(step) }} --  {{ step.totaltime }}s
              </div>
              <!-- <div style="display:inline-block;margin-right:40px;" class="grid-content bg-purple">
                 {{ getContent(step) }}
              </div>
              <div style="display:inline-block;margin-right:40px;" class="grid-content bg-purple">
                 {{ step.totaltime }}s
              </div> -->
              <el-button  v-show="tabName === 'second'"
                          style="float: right;margin-bottom:5px;margin-top:-5px;"
                          :type="getButtonType(step)"
                          size="small"
                          @click="onExecuteClick(step)">
                <template v-if="!step.state || step.state === 0">
                  {{ $t("openatc.dutyroute.executen") }}
                </template>
                <template v-else>
                  {{ $t("openatc.dutyroute.cancel") }}
                </template>
              </el-button>
            </div>
          </div>
          <!-- <div class="resttime"
               v-show="tabName === 'second' && step.state === 1">
            {{ step.resttime }}
          </div> -->
          <div class="card-div">
            <route-card
              :node="step"
              :tabName="tabName"
              :isShowVideo="route.isShowVideo"
              ref="routeCard"
              @research="research"
              @getTscControl="getTscControl"
            ></route-card>
          </div>
        <!-- </el-timeline-item>
      </el-timeline> -->
      </el-row>
    </el-scrollbar>
    <select-control v-show="false" ref="selectControlName"></select-control>
  </div>
</template>

<script>
import RouteCard from './routeCard'
import { getTscControl } from '../../../../api/control'
import { ExecuteViproute } from '../../../../api/service'
import { getMessageByCode } from '../../../../utils/responseMessage'
import ServiceUtil from '../../../../views/Service/serviceUtil.js'
import SelectControl from '../../../../views/Service/components/SelectControl'
export default {
  name: 'routeState',
  components: {
    RouteCard,
    SelectControl
  },
  props: {
    route: {
      type: Object
    },
    tabName: {
      type: String,
      default: 'second'
    }
  },
  data () {
    return {
      cycleTextMap: new Map(),
      node: {},
      cycleText: '',
      activeIndex: 0,
      isPopoverShow: true,
      showIndex: -1,
      intervalId: 0
    }
  },
  watch: {
    route (val) {
      if (!val) { return false }
      let devs = val.devs
      if (!devs || devs.length === 0) {
        return false
      }
      let isOn = false
      for (let dev of devs) {
        let cycleText = this.cycleTextMap.get(dev.agentid)
        dev.cycleText = cycleText
      }
      for (let dev of devs) {
        if (dev.state === 1) {
          let _this = this
          if (_this.intervalId !== 0) { // 已有定时器
            return false
          }
          isOn = true
          _this.intervalId = setInterval(function () {
            _this.$emit('research')
          }, 2000)
        }
      }
      if (!isOn) {
        clearInterval(this.intervalId)
        this.intervalId = 0
      }
    },
    deep: true
  },
  created () {
    this.serviceUtil = new ServiceUtil()
  },
  methods: {
    getTscControl (res) {
      let agentid = res.data.data.agentid
      let data = res.data.data.data
      let syncTime = data.syncTime
      let cycle = data.cycle
      let routeCopy = JSON.parse(JSON.stringify(this.route))
      for (let dev of routeCopy.devs) {
        if (dev.agentid === agentid) {
          dev.syncTime = syncTime
          dev.cycle = cycle
          let cycleText = dev.cycle ? ' -- ' + dev.cycle + '/' + dev.syncTime : ''
          this.cycleTextMap.set(dev.agentid, cycleText)
          dev.cycleText = cycleText
        }
      }
      this.route = routeCopy
    },
    getType (state, index) {
      let res = 'primary'
      if (this.showIndex === index) {
        res = 'warning'
      }
      if (state === 1) {
        res = 'success'
      }
      return res
    },
    onStepClick (index) {
      this.changeCard(index)
      this.$emit('onCardClick', this.route.devs[index])
    },
    changeCard (index) {
      this.activeIndex = index
      this.$refs.routeCard[index].show()
      this.showIndex = index
    },
    setCurrentRow (dev) {
      let index = -1
      for (let i = 0; i < this.route.devs.length; i++) {
        let d = this.route.devs[i]
        if (d.agentid === dev.agentid) {
          index = i
          break
        }
      }
      if (index >= 0) {
        this.changeCard(index)
      }
    },
    research () {
      this.$emit('research')
    },
    getTag (row) {
      if (row.stateName === 'DOWN') {
        return {
          label: this.$t('openatc.devicemanager.offline'),
          type: 'info'
        }
      } else if (row.stateName === 'UP') {
        return {
          label: this.$t('openatc.devicemanager.online'),
          type: 'success'
        }
      } else {
        return {
          label: this.$t('openatc.devicemanager.fault'),
          type: 'danger'
        }
      }
    },
    getPattern () {
      let _this = this
      return new Promise((resolve, reject) => {
        let agentid = _this.node.agentid
        let pattern
        getTscControl(agentid).then(data => {
          let res = data.data
          if (!res.success) {
            let parrenterror = getMessageByCode(data.data.code, _this.$i18n.locale)
            if (data.data.data) {
              // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, _this.$i18n.locale)
                _this.$message.error(parrenterror + ',' + childerror)
              }
            } else {
              _this.$message.error(parrenterror)
            }
            return
          }
          pattern = res.data.data
          resolve(pattern)
        })
      })
    },
    async onExecuteClick (node) {
      this.node = node
      if (this.node.control === 4 && (!this.node.state || this.node.state === 0)) {
        let pattern = await this.getPattern()
        let patternId = pattern.patternid
        let configPatternId = this.node.terminal
        let configMsg = ''
        if (configPatternId !== patternId) {
          configMsg = this.$t('openatc.dutyroute.configPattern') + configPatternId + ', ' + this.$t('openatc.dutyroute.currentPattern') + patternId + ` 。`
        }
        let infoMsg = this.$t('openatc.common.tipsmodaltitle')
        let valueMsg = this.node.value ? this.node.value : this.$t('openatc.dutyroute.nextStage')
        let comfirmMsg = configMsg + this.$t('openatc.dutyroute.executePattern') + this.$t('openatc.dutyroute.controlType4') + ', ' + this.$t('openatc.patternstatistic.pattern') + patternId + ', ' + this.$t('openatc.dutyroute.stage') + ': ' + valueMsg + ' ?'
        this.$confirm(comfirmMsg, infoMsg, {
          confirmButtonText: this.$t('openatc.button.OK'),
          cancelButtonText: this.$t('openatc.button.Cancel'),
          type: 'info'
        }).then(() => {
          this.executeViproute(node)
        }).catch(() => {
          this.$message.warning(this.$t('openatc.common.canceloperate'))
        })
      } else {
        this.executeViproute(node)
      }
    },
    executeViproute (node) {
      let reqData = {
        'agentid': node.agentid,
        'viprouteid': node.viprouteid,
        'operation': 1
      }
      if (node.state === 1) {
        reqData.operation = 0
      }
      // this.isBtnDisabled = true
      ExecuteViproute(reqData).then(res => {
        // this.isBtnDisabled = false
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return false
        } else {
          if (res.data.data && res.data.data.data) {
            let success = res.data.data.data.success
            if (success !== 0) {
              // 手动面板控制提示
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return false
            }
          }
          this.$message.success(this.$t('openatc.common.operationsuccess'))
        }
        this.$emit('research')
      })
    },
    getButtonType (node) {
      let res = 'warning'
      if (!node.state || node.state === 0) {
        res = 'primary'
      }
      return res
    },
    getControlName (control) {
      let res
      res = this.$refs.selectControlName.getNameById(control)
      return res
    },
    getContent (row) {
      let res = this.serviceUtil.getContent(row)
      // if (res === '') {
      //   res = row.controlName
      // }
      return res
    }
  }
}

</script>
<style scoped>
.block {
  width: auto;
  height: 750px;
  /* margin: 0 -30px 0 -30px; */
  /* margin-left: -30px; */
  /* border: 1px solid red; */
}
.card-div {
  overflow: hidden;
  padding-left: 0px;
  width: 100%;
}
.block >>> .el-scrollbar__wrap {
  overflow-x: hidden;
}

.block >>> .el-timeline-item__node--large {
  left: -4px;
  width: 20px;
  height: 20px;
}
.block >>> .el-timeline-item__tail {
  position: absolute;
  left: 4px;
  height: 100%;
  border-left: 5px solid #e4e7ed;
}
.resttime {
  padding: 5px;
  margin-top: 5px;
}
</style>
